<template>
    <div class="enterpriseForm">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
            <el-row>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                    <el-form-item label="用户名" prop="user.nickName">
                        <el-input v-model="form.user.nickName" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                    <el-form-item label="用户账号" prop="user.userName">
                        <el-input v-model="form.user.userName" placeholder="请输入登录账号"
                            @blur="handleOnlyVal('用户账号', form.user.userName)"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                    <el-form-item label="设置密码" prop="user.password">
                        <el-popover placement="right" trigger="focus" width="240">
                            <p v-show="passwordIndex == -1">
                                请至少输入6个字符。请不要使用容易被猜到的密码。
                            </p>
                            <div v-show="passwordIndex == 0">
                                <p style="font-size: 16px; color: #e47470">强度：太短</p>
                                <el-progress :percentage="50" status="exception"></el-progress>
                                <p style="padding-top: 5px">
                                    请至少输入6个字符。请不要使用容易被猜到的密码。
                                </p>
                            </div>
                            <div v-show="passwordIndex == 1">
                                <p style="font-size: 16px; color: #e47470">强度：弱</p>
                                <el-progress :percentage="50" status="exception"></el-progress>
                                <p style="padding-top: 5px">
                                    请至少输入6个字符。请不要使用容易被猜到的密码。
                                </p>
                            </div>
                            <div v-show="passwordIndex >= 2">
                                <p style="font-size: 16px; color: #7ebf50">强度：安全</p>
                                <el-progress :percentage="100" status="success"></el-progress>
                                <p style="padding-top: 5px">
                                    请至少输入6个字符。请不要使用容易被猜到的密码。
                                </p>
                            </div>
                            <el-input slot="reference" v-model="form.user.password" placeholder="请输入登录密码" maxlength="16"
                                show-password>
                            </el-input>
                        </el-popover>
                    </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                    <el-form-item label="确认密码" prop="user.checkpassword">
                        <el-input show-password v-model="form.user.checkpassword" placeholder="确认密码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                    <el-form-item label="手机号" prop="user.phone">
                        <el-input v-model.number="form.user.phone" placeholder="请输入手机号"
                            @blur="handleOnlyVal('手机号码', form.user.phone)"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                    <el-form-item label="是否实名" prop="user.iuiCertification">
                        <el-radio-group v-model="form.user.iuiCertification">
                            <el-radio label="1">是</el-radio>
                            <el-radio label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="form.user.iuiCertification=='1'">
                    <el-form-item label="身份证号" prop="user.identityId">
                        <el-input @input="changeCard" v-model="form.user.identityId" placeholder="请输入身份证号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="form.user.iuiCertification=='1'">
                    <el-form-item label="性别" prop="user.sex">
                        <el-radio-group v-model="form.user.sex" :disabled="true">
                            <el-radio label="0">男</el-radio>
                            <el-radio label="1">女</el-radio>
                            <!-- <el-radio label="2">保密</el-radio> -->
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="form.user.iuiCertification=='1'">
                    <el-form-item label="真实姓名" prop="user.realName">
                        <el-input v-model="form.user.realName" placeholder="请输入真实姓名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="form.user.iuiCertification=='1'">
                    <el-form-item label="专业领域" prop="user.managerIntroduction">
                        <el-input type="textarea" show-word-limit  maxlength="500" v-model="form.user.managerIntroduction" placeholder="请输入专业领域"></el-input>
                    </el-form-item>
                </el-col>
                <div>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="form.user.iuiCertification=='1'">
                        <el-form-item class="newIpt" ref="headimgUpload1" label="身份证正面" prop="user.identityJust">
                            
                            <el-upload class="avatar-uploader" :action="imageUploadUrl" :show-file-list="false"
                                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                                :on-error="handleError">
                                <img v-if="imgUrl" :src="imgUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            <p class="uploadTip">上传图片不超过10M，且只能上传jpg、png类型</p>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="form.user.iuiCertification=='1'">
                        <el-form-item class="newIpt" ref="headimgUpload2" label="身份证反面" prop="user.identityBack">
                            
                            <el-upload class="avatar-uploader" :action="imageUploadUrl" :show-file-list="false"
                                :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload"
                                :on-error="handleError2">
                                <img v-if="imgUrl2" :src="imgUrl2" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            <p class="uploadTip">上传图片不超过10M，且只能上传jpg、png类型</p>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item class="newIpt" label="头像" prop="user.avatar">
                            
                            <el-upload class="avatar-uploader" :action="imageUploadUrl" :show-file-list="false"
                                :on-success="handleAvatarSuccess3" :before-upload="beforeAvatarUpload"
                                :on-error="handleError3">
                                <img v-if="imgUrl3" :src="imgUrl3" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            <p class="uploadTip">上传图片不超过10M，且只能上传jpg、png类型</p>
                        </el-form-item>
                    </el-col>
                </div>

            </el-row>
        </el-form>
        <div class="registerBtn">
            <el-button class="prevBtn" @click="prevBtn()">上一步</el-button>
            <el-button class="colorBtn" @click="handleSubmit()" :loading="loading" type="primary">立即注册</el-button>
        </div>
    </div>
</template>
<script>
import { personReg, selectCom, selectPark, getOnly, sendPhoneCode } from "@/request/api/register"
import { aesEncrypt, desEncrypt } from "@/utils/crypto.js";
import rulesUtil from "@/utils/rules"
import { sendEmail2 } from "@/request/api/login"
import { keyVal } from "@/request/api/link"
export default {
    data() {
        // 确认密码
        var checkPass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.form.user.password) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            passwordIndex: -1,
            loading:false,
            comData: [],
            form: {
                type: "0", //注册类型(0个人用户 1机构用户 2专家)
                user: {
                    //个人/机构/专家 公用信息字段
                    nickName: "", //用户名
                    userName: "", //用户账号
                    password: "", //用户密码 加密模式为AES加密（AES/ECB/PKCS5Padding）key为：!Ae357S07&iKk#24"
                    phone: "", //手机号
                    avatar: "", //头像地址
                    iuiCertification: "0", //是否实名认证 0未实名 1实名
                    //个人用户注册实名信息字段
                    managerIntroduction: "",		//专业领域(500长文本)
                    sex: "",	//性别（0男 1女 2保密）
                    identityId: "",//身份证号
                    realName: "",//真实姓名
                    identityJust: "",//身份证正面照片
                    identityBack: "",//身份证反面照片
                },
            },
            
            rules: {
                user: {
                    userName: [
                        { required: true, validator: rulesUtil.FormValidate.Form().validateCode, trigger: 'blur' },
                    ],
                    nickName: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ],
                    phone: [
                        { validator: rulesUtil.FormValidate.Form().validatePhoneNo, trigger: 'blur' },
                    ],
                    password: [
                        { required: true, validator: rulesUtil.FormValidate.Form().validatePsdReg, trigger: 'blur' },
                    ],
                    iuiCertification: [
                        { required: true, message: '请选择', trigger: 'change' },
                    ],
                    sex: [
                        { required: true, message: '请选择', trigger: 'change' },
                    ],
                    identityId: [
                        { required: true, validator: rulesUtil.FormValidate.Form().cardID, trigger: 'blur' },
                    ],
                    checkpassword: [
                        {
                            required: true,
                            validator: checkPass2,
                            trigger: "blur",
                        },
                    ],
                    identityJust: [
                        { required: true, message: '请上传', trigger: 'change' },
                    ],
                    identityBack: [
                        { required: true, message: '请上传', trigger: 'change' },
                    ],
                    // avatar: [
                    //     { required: true, message: '请上传', trigger: 'change' },
                    // ],
                    realName: [
                        { required: true, message: '请输入真实姓名', trigger: 'blur' },
                    ],
                    // managerIntroduction: [
                    //     { required: true, message: '请输入专业领域', trigger: 'blur' },
                    // ],
                }

            },
            imageUploadUrl: '/dev-api/file/upload/uploadNotQR',
            imgUrl: '',
            imgUrl2: '',
            imgUrl3: '',
            parkData: [],
            selectParams: {
                registrationType: null,//机构类型
                parkId: null//园区id
            },
            btnTxt: "获取验证码",//短信验证码提示
            disabled: false,//短信-是否可选
            time: 60,//短信-倒计时开始时间
            btnTxt2: "获取验证码",//手机验证码文字
            disabled2: false,//手机验证码-是否可选
            time2: 60,//手机验证码-倒计时开始时间
            staffTypeData: []
        }
    },
    created() {
    },
    methods: {
        // 选择机构类型
        getTypeVal(val) {
            this.selectParams.registrationType = val
            this.getRegType()
            if (val !== '9') {
                this.form.iuiCertification = '1'
            } else {
                this.form.iuiCertification = '0'
            }
            if (val === '9') {
                this.form.parkId = ''
                this.form.companyId = ''

            }
        },
        // 判断密码强弱
        checkPassWord(value) {
            // 0： 表示第一个级别 1：表示第二个级别 2：表示第三个级别
            // 3： 表示第四个级别 4：表示第五个级别
            var modes = 0;
            if (value.length < 6) {
                //最初级别
                return modes;
            }
            if (/\d/.test(value)) {
                //如果用户输入的密码 包含了数字
                modes++;
            }
            if (/[a-zA-Z]/.test(value)) {
                //如果用户输入的密码 包含了小写的a到z
                modes++;
            }
            // if (/[A-Z]/.test(value)) {
            //     //如果用户输入的密码 包含了大写的A到Z
            //     modes++;
            // }
            if (/\W/.test(value)) {
                //如果是非数字 字母 下划线
                modes++;
            }
            switch (modes) {
                case 1:
                    return 1;
                    break;
                case 2:
                    return 2;
                    break;
                case 3:
                    return 3;
                    break;
            }
        },
        // 下一步-结果页面
        handleSubmit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.loading=true
                    let params = JSON.parse(JSON.stringify(this.form));
                    params.user.password = aesEncrypt(this.form.user.password);
                    console.log(params,'1111')
                    personReg(params).then(res => {
                        this.loading=false
                        if (res.data.code === 200) {
                            this.$message({
                                message: '注册成功!',
                                type: 'success'
                            });
                            this.$emit('hanldeResult')
                        } else {
                            this.$message.error(res.data.message);
                        }
                    })
                }
            });
        },
        // 上传文件成功-身份证正面
        handleAvatarSuccess(response, file) {
            this.imgUrl = URL.createObjectURL(file.raw);
            this.form.user.identityJust = response.message;
            this.$refs.headimgUpload1.clearValidate(); // 关闭校验
        },
        // 上传文件失败-身份证正面
        handleError(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因：${errInfo.message}`);
        },
        // 上传文件成功-身份证反面
        handleAvatarSuccess2(response, file) {
            this.imgUrl2 = URL.createObjectURL(file.raw);
            this.form.user.identityBack = response.message;
            this.$refs.headimgUpload2.clearValidate(); // 关闭校验
        },
        // 上传文件失败-身份证反面
        handleError2(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因：${errInfo.message}`);
        },
        // 上传文件成功-人脸照片
        handleAvatarSuccess3(response, file) {
            this.imgUrl3 = URL.createObjectURL(file.raw);
            this.form.user.avatar = response.message;
        },
        // 上传文件失败-人脸照片
        handleError3(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因：${errInfo.message}`);
        },
        // 限制上传的类型
        beforeAvatarUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error("上传图片大小不能超过 10M!");
                return false;
            }
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "jpg" || testmsg === "JPG";
            const extension2 = testmsg === "png" || testmsg === "PNG";
            if (!extension && !extension2) {
                this.$message({
                    message: "上传图片只能是 jpg, png格式!",
                    type: "error",
                });
                return false;
            }
        },
        // 上一步,返回类型页面
        prevBtn() {
            this.$emit('handleType')
        },
        // 用户注册校验唯一性--用户账号、手机号码、邮箱账号
        handleOnlyVal(type, val) {
            if (val) {
                let params = {
                    type: type,
                    value: val
                }
                getOnly(params).then(res => {
                    if (res.data.code === 500) {
                        this.$message({
                            message: res.data.message,
                            type: 'warning'
                        });
                        if (type === '用户账号') {
                            this.form.user.userName = ''
                        } else if (type === '手机号码') {
                            this.form.user.phone = ''
                        } 
                    }
                })
            }

        },
        //发送手机验证码倒计时-邮箱
        timer() {
            if (this.time > 0) {
                this.disabled = true;
                this.time--;
                this.btnTxt = this.time + "秒";
                setTimeout(this.timer, 1000);
            } else {
                this.time = 0;
                this.btnTxt = "获取验证码";
                this.disabled = false;
            }
        },
        // 发送手机验证码-邮箱
        getSendEmail(email) {
            let params = {
                email
            }
            sendEmail2(params).then((res) => {
                if (res.data.code === 200) {
                    this.$notify({
                        title: "成功",
                        message: res.data.message,
                        type: "success",
                    });
                    this.time = 60;
                    this.timer();
                } else {
                    this.$notify({
                        title: "错误",
                        message: res.data.message,
                        type: "error",
                    });
                }
            });
        },
        // 点击获取验证码-邮箱
        logInCode() {
            if (this.form.email === "") {
                this.$message({
                    message: "请输入邮箱！",
                    type: "warning",
                });
                return false;
            }
            this.getSendEmail(this.form.email);
        },
        //发送手机验证码倒计时-手机号
        timer2() {
            if (this.time2 > 0) {
                this.disabled2 = true;
                this.time2--;
                this.btnTxt2 = this.time2 + "秒";
                setTimeout(this.timer2, 1000);
            } else {
                this.time2 = 0;
                this.btnTxt2 = "获取验证码";
                this.disabled2 = false;
            }
        },
        // 发送手机验证码-手机号
        getSendPhone(phone) {
            let params = {
                phone
            }
            sendPhoneCode(params).then((res) => {
                if (res.data.code === 200) {
                    this.$notify({
                        title: "成功",
                        message: res.data.message,
                        type: "success",
                    });
                    this.time2 = 60;
                    this.timer2();
                } else {
                    this.$notify({
                        title: "错误",
                        message: res.data.message,
                        type: "error",
                    });
                }
            });
        },
        // 点击获取验证码-手机号
        logInCode2() {
            if (this.form.phone === "") {
                this.$message({
                    message: "请输入手机号！",
                    type: "warning",
                });
                return false;
            }
            this.getSendPhone(this.form.phone);
        },
        // 选择证件类型
        changeType() {
            this.form.identityId = ''
            // 去掉某个属性的表单校验
            this.$refs.form.clearValidate('identityId')
        },
        // 输入身份证事件
        changeCard(val) {
            // let IDcard = val.target.value
            if (val.length == 18) {
                // 根据身份证号判断性别，并赋值
                let sex = val.substring(16, 17);// IDcard为用户输入的身份证号码
                var val = sex % 2 == 1 ? '男' : '女';
                if (val == '男') {
                    this.form.user.sex = '0'
                } else if (val == '女') {
                    this.form.user.sex = '1'
                }
            }
        }
    },
    watch: {
        "form.user.password": {
            handler: function (val, oldVal) {
                if (val.length == "") {
                    this.passwordIndex = -1;
                } else {
                    this.passwordIndex = this.checkPassWord(val);
                }
            },
        },
    },
}
</script>
<style lang="less" scoped>
@import "./common.less";
@import "../../view/register/register.less";
</style>

